package com.star.warmwinter.http.base;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.star.warmwinter.common.BaseActivity;
import com.star.warmwinter.http.config.ExceptionHandle;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Author: blackbai11
 * Date: 2017/7/19 16:31
 * Description: BaseObserver
 */
public abstract class BaseObserver<T> implements Observer<BaseEntity<T>> {

    private static final String TAG = BaseObserver.class.getSimpleName();
    private static final int RESPONSE_CODE_OK = 0;//服务端请求成功返回码

    private Context mContext;

    protected BaseObserver() {}

    public BaseObserver(Context cxt) {
        this.mContext = cxt;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        Log.d(TAG, "onSubscribe");
        onRequestStart();

        ((BaseActivity)mContext).addDisposable(d);
    }

    @Override
    public void onNext(BaseEntity<T> baseEntity) {
        onRequestEnd();
        if (baseEntity.getCode() == RESPONSE_CODE_OK) {
            onSuccess(baseEntity);
        } else {
            onFailure(baseEntity.getCode(), baseEntity.getMsg());
        }
    }

    /**
     * 服务器连接失败
     */
    @Override
    public void onError(Throwable e) {
        onRequestEnd();
        ExceptionHandle.ApiException apiException = ExceptionHandle.handleException(e);
        onFailure(apiException.code,apiException.message);
    }

    @Override
    public void onComplete() {
        Log.d(TAG, "onComplete");
    }

    /**
     * 服务器返回成功结果
     */
    protected abstract void onSuccess(BaseEntity<T> baseEntity);

    /**
     * 服务器返回失败结果
     */
    protected  void onFailure(int code, String message){
        Log.e(TAG, "请求失败code:"+code+",msg:"+message);
        if(code == ExceptionHandle.ERROR.HTTP_ERROR || code == ExceptionHandle.ERROR.NETWORK_ERROR && mContext != null){
            Toast.makeText(mContext, "网络连接失败,请检查您的网络或稍后重试", Toast.LENGTH_SHORT).show();
        }
        disposeEorCode(code,message);
    }


    /**
     * 请求开始
     */
    protected void onRequestStart() {
        //打开dialog
    }

    /**
     * 请求结束
     */
    protected void onRequestEnd() {
        //关闭dialog
    }

    /**
     * 对通用问题的统一拦截处理
     * @param code
     */
    private final void disposeEorCode(int code, String message) {
        switch (code) {
            case 101:
            case 401:
                //退回登录页重新登陆
                break;
        }
    }

}